<?php


namespace EchoPHP\Http;


use EchoPHP\Http\Response\RedirectResponse;

class Redirector {

    protected $request;

    public function __construct(Request $request) {
        $this->request = $request;
    }

    /**
     * 前往网站首页
     * @param int $status
     * @return RedirectResponse
     */
    public function home($status = 302) {
        $domain = $this->request->getDomain();
        return $this->to($domain, $status);
    }

    /**
     * 回到来源页
     * @param int $status
     * @param array $headers
     * @param null $fallback
     * @return RedirectResponse
     */
    public function back($status = 302, array $headers = [], $fallback = null) {
        $refer = $this->request->header()->get('referer');
        if ($refer) {
            return $this->to($refer, $status, $headers);
        }
        if (!$fallback) {
            return $this->to($fallback, $status);
        }
        return $this->home($status);
    }

    /**
     * 刷新当前页
     * @param int $status
     * @param array $headers
     * @return RedirectResponse
     */
    public function refresh($status = 302, array $headers = []) {
        $domain = $this->request->getDomain();
        $currentUrl = $this->request->getUrl();
        return $this->to($domain . $currentUrl, $status, $headers);
    }

    /**
     * 千万指定域名
     * @param $url
     * @param int $status
     * @param array $headers
     * @return RedirectResponse
     */
    public function to($url, $status = 302, array $headers = []) {
        return new RedirectResponse($url, $status, $headers);
    }
}